package com.xjm.api.admin;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjm.constant.Add;
import com.xjm.constant.Update;
import com.xjm.entity.model.ClassifyModel;
import com.xjm.entity.model.ProductsModel;
import com.xjm.entity.vo.PageVo;
import com.xjm.entity.vo.Result;
import com.xjm.service.ClassifyService;
import com.xjm.service.IProductsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xjm
 * @since 2025-02-27
 */
@RestController
@RequestMapping("/admin/product")
@RequiredArgsConstructor
public class ProductsController {
    private final IProductsService productsService;
    private final ClassifyService classifyService;


    @GetMapping("/classify")
    public Result<List<ClassifyModel>> classify() {
        return Result.success(classifyService.list());
    }

    @GetMapping
    public Result<PageVo<ProductsModel>> list(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "5") Long size
    ) {
        LambdaQueryWrapper<ProductsModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(ProductsModel::getId);
        return Result.success(productsService.page(new Page<>(page, size),wrapper));
    }

    @GetMapping("/{id}")
    public Result<ProductsModel> getById(@PathVariable Long id) {
        ProductsModel products = productsService.getById(id);
        if (products.getOther() != null){
            products.setOther(JSONUtil.parseArray(products.getOther()));
        }
        return Result.success(products);
    }

    @PostMapping
    public Result<ProductsModel> add(@Validated({Add.class}) @RequestBody ProductsModel productsModel) {
        if (productsModel.getOther() != null){
            productsModel.setOther(JSONUtil.toJsonStr(productsModel.getOther()));
        }
        productsService.save(productsModel);
        return Result.success();
    }

    @PutMapping
    public Result<ProductsModel> update(@Validated({Update.class}) @RequestBody ProductsModel productsModel) {
        System.out.println(productsModel);
        productsModel.setUpdatedTime(null);
        if (productsModel.getOther() != null){
            productsModel.setOther(JSONUtil.toJsonStr(productsModel.getOther()));
        }
        productsService.updateById(productsModel);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<ProductsModel> delete(@PathVariable Long id) {
        productsService.removeById(id);
        return Result.success();
    }
}
